from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse,HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt

from myadmin import models
from .indexViews import getNavData


#  前台 - 订单确认
def orderconfirm(request):
    # 接收被选中cart的id列表
    ids = request.GET.get('ids','').split(',')

    # 获取对应的cart对象
    data = models.Cart.objects.filter(id__in=ids)

    # 分配数据
    context = {'classify':getNavData,'carts':data}
    return render(request,'myhome/order.html',context)


# 订单 - 创建
def ordercreate(request):
    # 接收订单数据和获取用户
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    vipuser = request.session.get('vipUser')

    # 计算总价
    totalprice = 0
    # 查询购物车商品
    ids = data['ids'].split(',')
    carts = models.Cart.objects.filter(id__in=ids)
    for i in carts:
        totalprice += i.num * i.bid.price

    # 准备订单数据
    orderdata = {
        'uid' : models.Users.objects.get(id=vipuser['id']),
        'name' : data['name'],
        'phone' : data['phone'],
        'city' : data['city'],
        'address' : data['address'],
        'totalprice' : totalprice,
        'remark' : data['remark'],
    }
    # 创建订单
    orderobj = models.Order(**orderdata)
    orderobj.save()

    # 准备订单详情数据
    for i in carts:
        detailsdata = {
            'orderid' : orderobj,
            'bid' : i.bid ,
            'num' : i.num,
            'price' : i.bid.price,
        }
        # 创建订单详情
        detailsobj = models.OrderDetails(**detailsdata)
        detailsobj.save()

        # 从购物车删除已提交订单中的商品
        i.delete()

    # 跳转到支付页面
    url = reverse('myhome_orderpay',args=(orderobj.id,))
    return HttpResponseRedirect(url)


# 订单 - 发起支付请求
def orderpay(request,orderid):
    # orderid = request.GEt.get('orderid')
    print(orderid)
    return HttpResponse('发起支付请求')








